package com.ynkbny.config;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zelin.wang
 * @description 自定义拦截
 * @date 8/23/2023
 */
public class ShiroLoginFilter extends FormAuthenticationFilter {


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if (isAjax(request)) {
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            Map map= new HashMap<>();
            map.put("code",403);
            map.put("msg","登录认证失效，请重新登录!");
            map.put("data","");
            httpServletResponse.getWriter().write(JSONObject.toJSON(map).toString());
        } else {

            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            Map map = new HashMap<>();
            map.put("code",403);
            map.put("msg","未登录！");
            map.put("data","");
            httpServletResponse.getWriter().write(JSONObject.toJSON(map).toString());
        }
        return false;
    }
    private boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
